import React, {Component} from 'react';
import {View, SafeAreaView, TouchableOpacity, Text, Share} from 'react-native';
import {WebView} from 'react-native-webview';
import storage from '../../util/storage';
import MWebView from './webview';

export default class WebviewH5 extends MWebView {
  state = {
    token: ''
  }

  componentDidMount() {
    const params = this.props.params || {}
    this.props.navigation.setOptions({
      title: params.title
    })
    storage.getItem('userInfo').then(userInfo => {
      const token = userInfo ? userInfo.token : ''
      this.setState({ token })
    })
    this.props.navigation.addListener('focus', () => {
      this.refs.webview_ref.reload()
    });
  }

  render() {
    const runFirst = `
      window.MICRO_TASK = true;
      window.REACT_NATIVE = true;
      window.LOGIN_TOKEN = "${this.state.token}";
      true; // note: this is required, or you'll sometimes get silent failures
    `;
    const params = this.props.params || {}
    return (
      <SafeAreaView style={{flex: 1, paddingTop: 50}}>
        <WebView
          ref={'webview_ref'}
          source={{
            uri: params.url,
            headers: { 'Cache-Control':'no-cache'}
          }}
          domStorageEnabled={true}
          injectedJavaScriptBeforeContentLoaded={runFirst}
          scrollEnabled={true}
          javaScriptEnabled={true}
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
          onMessage={(event) => {
            this.handleMessage(event);
          }}
        />
      </SafeAreaView>
    );
  }
}
